const mongoose = require('mongoose');
const DBUtils = require('./utils');
const md5 = require('md5-node');
const log = require('../libs/log4js')('USERVALIDE');

const accountUser = mongoose.Schema({
  userName: String,
  createDate: String,
  updateDate: String,
  openid: String,
  token: String,
  tokenOutTime: Number,
  id: String,
  pwd: String
});

const Test = mongoose.model('accountUser', accountUser);
const db = new DBUtils({
  DB: Test,
  logName: 'ACCOUNTUSER'
});
// const insert = db.insert.bind(db);
// const query = db.queryAll.bind(db);
// const update = db.update.bind(db);
// const del = db.deleteOne.bind(db);
// const delM = db.deleteMany.bind(db);

function buildToken(openID) {
  const time = new Date().getTime();
  return {
    token: md5(openID + time.toString(16)),
    time: time + 2592000000 // 30天过期一次
  };
}

async function sigin(data) {
  let token = buildToken(data.openid);
  data.token = token.token;
  data.tokenOutTime = token.time;
  data.id = md5(data.openid);
  let flag = await db.insert({
    data
  });
  if (flag) {
    return data;
  } else {
    return false;
  }
}

async function wxlogin(user, token) {
  if (!user && !token) return false;
  if (!user && token) {
    user = await getUserByToken(token);
    if (!user || user.length === 0) {
      log.debug('没有找到更新的用户');
      return false;
    }
    user = user[0];
  }
  let tokenMsg = buildToken(user.openid);
  log.debug('新的token', tokenMsg);
  log.debug('更新的user', user);
  const flag = await db.update({
    queryData: {
      openid: user.openid
    },
    data: {
      token: tokenMsg.token,
      tokenOutTime: tokenMsg.time
    }
  });
  await global.$redis.set(tokenMsg.token, user.id);
  if (flag) {
    return tokenMsg;
  } else {
    return false;
  }
}

async function adminLogin(userName, pwd) {
  let user = await db.queryAll({
    queryData: {
      userName,
      pwd: md5(pwd)
    }
  });
  log.debug('查询结果', user);
  if (user && user[0]) {
    let tokenMsg = buildToken(userName);
    log.debug('新的token', tokenMsg);
    log.debug('更新的user', user);
    user = user[0];
    global.$redis.del(user.token)
    const flag = await db.update({
      queryData: {
        userName
      },
      data: {
        token: tokenMsg.token,
        tokenOutTime: tokenMsg.time
      }
    });
    // tokenMsg.token,
    // 三个小时有效期
    await global.$redis.set(tokenMsg.token, user.id, 10800);
    if (flag) {
      return tokenMsg;
    }
  }
  return false;
}

function getUserByOpenid(openid) {
  return db.queryAll({
    queryData: {
      openid
    }
  });
}

function getUserById(id) {
  return db.queryAll({
    queryData: {
      id
    }
  });
}

function getUserByToken(token) {
  return db.queryAll({
    queryData: {
      token
    }
  });
}

function getUserByUserName(userName) {
  return db.queryAll({
    queryData: {
      userName
    }
  });
}

async function validToken(token, ctx) {
  log.debug('开始校验token');
  let user = await global.$redis.get(token);
  log.debug('获取的用户', user);
  if (!user) {
    log.debug('token 校验失败, 未找到用户');
    return '0';
  }
  ctx.request.body.__userId = user;
  return '2';
}

module.exports = {
  sigin,
  getUserByOpenid,
  wxlogin,
  validToken,
  getUserByUserName,
  adminLogin,
  getUserById
};
